import { ref } from 'vue';
import { defineStore } from 'pinia';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { logOperation } from '@/utils/log';

// 定义后端API接口路径
const API_URL = import.meta.env.VITE_API_BASE_URL;

export const useAuthStore = defineStore('auth', () => {
    const admin = ref(null);
    const loginTime = ref(null);
    const timeoutDuration = 60 * 60 * 1000;
    let timeoutInterval = null; // 新增定时器引用

    // 获取管理员信息
    const getAdmin = () => {
        const storedAdmin = localStorage.getItem('admin');
        return storedAdmin ? JSON.parse(storedAdmin) : null;
    };

    // 检查是否登录
    const isAuthenticated = () => {
        return admin.value !== null && !isSessionExpired();
    };

    // 检查会话是否过期
    const isSessionExpired = () => {
        if (!loginTime.value) return true;
        return Date.now() - loginTime.value > timeoutDuration;
    };

    // 登录
    const login = async ({ account, passwd }) => {
        try {
            const { data } = await axios.post(`${API_URL}/v1/admin/login`, {
                account,
                passwd,
            });

            if (data.code === 2000) {
                // Check if the account is disabled
                if (data.response.status === '禁用') {
                    ElMessage.error('账号已被禁用，请联系管理员');
                    return false;
                }

                admin.value = data.response;
                loginTime.value = Date.now();
                localStorage.setItem('admin', JSON.stringify(data.response));
                localStorage.setItem('loginTime', loginTime.value);
                ElMessage.success('登录成功');
                await router.push('/');
                startTimeoutCheck();
                // 记录操作日志
                await logOperation('用户登录', `${getAdmin().name} 登录成功`);
                return true;
            } else if (data.code === 4002) {
                ElMessage.error(data.response.message || '账号已被禁用，请联系管理员');
                return false;
            } else {
                ElMessage.error(data.response.message || '登录失败，请检查凭证');
                return false;
            }
        } catch (error) {
            ElMessage.error('登录失败，请稍后重试');
            console.error('Login error:', error);
            return false;
        }
    };

    // 登出
    const logout = async () => {
        const currentAdmin = getAdmin();
        if (currentAdmin) {
            await logOperation('用户退出', `${currentAdmin.name} 退出登录`);
        }
        if (timeoutInterval) {
            clearInterval(timeoutInterval); // 登出时清理定时器
            timeoutInterval = null;
        }
        admin.value = null;
        loginTime.value = null;
        localStorage.removeItem('admin');
        localStorage.removeItem('loginTime');
        localStorage.removeItem('breadcrumb');
        await router.push('/login');
    };

    // 检查超时
    const checkTimeout = () => {
        if (isAuthenticated() && isSessionExpired()) {
            logout();
            ElMessage.warning('会话已超时，请重新登录');
        }
    };

    // 启动超时检查
    const startTimeoutCheck = () => {
        if (timeoutInterval) clearInterval(timeoutInterval); // 清除旧定时器
        timeoutInterval = setInterval(checkTimeout, 60 * 1000);
    };

    // 初始化认证状态
    const initializeAuth = () => {
        const storedAdmin = getAdmin();
        const storedTime = localStorage.getItem('loginTime');
        if (storedAdmin && storedTime) {
            admin.value = storedAdmin;
            loginTime.value = parseInt(storedTime);

            // Check if the stored admin is disabled
            if (admin.value.status === '禁用') {
                logout();
                ElMessage.error('您的账号已被禁用，请联系管理员');
                return;
            }

            if (isSessionExpired()) {
                logout();
                ElMessage.warning('会话已超时，请重新登录');
            } else {
                startTimeoutCheck();
            }
        }
    };

    return {
        admin,
        getAdmin,
        isAuthenticated,
        login,
        logout,
        initializeAuth,
    };
});